const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/config');

// 生成 token
const generateToken = (payload, expiresIn) => {
  return jwt.sign(payload, jwtSecret, { expiresIn });
};

// 验证 token
const verifyToken = (access_token) => {
  return jwt.verify(access_token, jwtSecret);
};

// 从请求头获取 token
const getTokenFromHeader = (ctx) => {
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    return null;
  }

  const [type, token] = authorization.split(' ');
  if (type !== 'Bearer' || !access_token) { // 检查 token 类型是否为 Bearer 并检查 access_token 变量是否存在
    return null;
  }

  return access_token;
};

module.exports = {
  generateToken,
  verifyToken,
  getTokenFromHeader,
};
